import yaml, os, shutil, re, inspect

from nothing import Nothing

BASE_PATH = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))

SETTINGS_FILENAME = os.path.join(BASE_PATH, "settings.yaml")

class _Settings(object):

	def __init__(self, filename = SETTINGS_FILENAME):
		self._filename = filename
		with open(self._filename, "r") as settings_yaml:
			data = yaml.load(settings_yaml.read())

		for attr1, value1 in data.iteritems():
			setattr(self, attr1, Nothing())
			for attr2, value2 in value1.iteritems():
				if (attr1 == "path" and attr2 in ('cat', 'data', 'sub', 'log', 'holiday')):
					setattr(getattr(self, attr1), attr2, os.path.join(BASE_PATH, value2))
					
				elif (attr1 == "podcast" and attr2 == "pods"):
					setattr(getattr(self, attr1), attr2, Nothing())
					for attr3, value3 in value2.iteritems():
						new_value3_list = []
						for item in value3:
							element = Nothing()
							for key, value in item.iteritems():
								setattr(element, key, value)
							new_value3_list.append(element)
							
						setattr(getattr(getattr(self, attr1), attr2), attr3, new_value3_list)

				elif (attr1 == "log" and attr2 == "type") or (attr1 == "cat" and attr2 == "sub"):
					setattr(getattr(self, attr1), attr2, Nothing())
					for attr3, value3 in value2.iteritems():
						setattr(getattr(getattr(self, attr1), attr2), attr3, Nothing())

						for attr4, value4 in value3.iteritems():
							setattr(getattr(getattr(getattr(self, attr1), attr2), attr3), attr4, value4)

				elif (attr1 == "date" and attr2 == "holiday") or (attr1 == "mpd" and attr2 == "config") or (attr1 == "favorite" and attr2 == "tag") or (attr1 == "sql" and attr2 in ("connect_args", "poolclass")):
					setattr(getattr(self, attr1), attr2, Nothing())
					for attr3, value3 in value2.iteritems():
						setattr(getattr(getattr(self, attr1), attr2), attr3, value3)

				elif (attr1 == "tags"):
					setattr(getattr(self, attr1), attr2, Nothing())
					for attr3, value3 in value2.iteritems():
						if (attr3 == "values"):
							setattr(getattr(getattr(self, attr1), attr2), attr3, Nothing())

							for attr4, value4 in value3.iteritems():
								setattr(getattr(getattr(getattr(self, attr1), attr2), attr3), attr4, value4)
						else:
							setattr(getattr(getattr(self, attr1), attr2), attr3, value3)

				elif attr1 == "types":
					setattr(getattr(self, attr1), attr2, Nothing())
					for attr3, value3 in value2.iteritems():
						if attr3 == "tags":
							setattr(getattr(getattr(self, attr1), attr2), attr3, Nothing())

							for attr4, value4 in value3.iteritems():
								# Some hacking to make Apple's tags process correctly.
								setattr(getattr(getattr(getattr(self, attr1), attr2), attr3), attr4, value4.encode("utf8").strip("\xc2"))

						else:
							setattr(getattr(getattr(self, attr1), attr2), attr3, value3)

				elif attr1 == "re":
					setattr(getattr(self, attr1), attr2, re.compile(value2))

				else:
					setattr(getattr(self, attr1), attr2, value2)

		if not hasattr(self.sql, "echo"):
			setattr(self.sql, "echo", False)
			self.save()

	def save(self):
		data = {}
		for attr1, value1 in self.__dict__.iteritems():
			if attr1 == "_filename":
				continue
			data[attr1] = {}
			for attr2, value2 in value1.__dict__.iteritems():
				if (attr1 == "path" and attr2 in ('cat', 'data', 'sub', 'log', 'holiday')):
					data[attr1][attr2] = value2[len(BASE_PATH) + 1:]

				elif (attr1 == "podcast" and attr2 == "pods"):
					data[attr1][attr2] = {}
					for attr3, value3 in value2.__dict__.iteritems():
						new_value3_list = []
						for item in value3:
							element = {}
							for key, value in item.__dict__.iteritems():
								element[key] = value
							new_value3_list.append(element)
						
						data[attr1][attr2][attr3] = new_value3_list	
				elif (attr1 == "log" and attr2 == "type") or (attr1 == "cat" and attr2 == "sub"):
					data[attr1][attr2] = {}
					
					for attr3, value3 in value2.__dict__.iteritems():
						data[attr1][attr2][attr3] = {}

						for attr4, value4 in value3.__dict__.iteritems():
							data[attr1][attr2][attr3][attr4] = value4

				elif (attr1 == "date" and attr2 == "holiday") or (attr1 == "mpd" and attr2 == "config") or (attr1 == "favorite" and attr2 == "tag") or (attr1 == "sql" and attr2 in ("connect_args", "poolclass")):
					data[attr1][attr2] = {}
					
					for attr3, value3 in value2.__dict__.iteritems():
						data[attr1][attr2][attr3] = value3

				elif (attr1 == "tags"):
					data[attr1][attr2] = {}
					for attr3, value3 in value2.__dict__.iteritems():
						if (attr3 == "values"):
							data[attr1][attr2][attr3] = {}

							for attr4, value4 in value3.__dict__.iteritems():
								data[attr1][attr2][attr3][attr4] = value4
						else:
							data[attr1][attr2][attr3] = value3

				elif attr1 == "types":
					data[attr1][attr2] = {}
					
					for attr3, value3 in value2.__dict__.iteritems():
						if attr3 == "tags":
							data[attr1][attr2][attr3] = {}
							for attr4, value4 in value3.__dict__.iteritems():
								if "\xA9" in value4:
										# Gotta put the Apple tags back in the correct form so that I can properly save the file.
										data[attr1][attr2][attr3][attr4] = value4.replace("\xA9", "\xc2\xA9").decode("utf8")
								else:
									data[attr1][attr2][attr3][attr4] = value4

						else:
							data[attr1][attr2][attr3] = value3

				elif attr1 == "re":
					data[attr1][attr2] = value2.pattern
				else:
					data[attr1][attr2] = value2

		if os.path.exists(self._filename):
			shutil.move(self._filename, "{filename}.{bak}".format(filename = self._filename, bak = self.ext.bak))

		with open(self._filename, "w") as f:
			f.write(yaml.dump(data, default_flow_style = False, indent = 4, encoding = "ascii"))
		


settings = _Settings()

if __name__ == "__main__":
	print settings.log.type.xdh_logging.debug

	print settings.podcast.pods.finance[0].title
